package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static long tokenExpiration = 24 * 60 * 60 * 1000L; //24个小时
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes()); //秘钥

    /**
     * 创建JWT令牌   token       头(算法名称(HS256)、JWT类型(JWT)).负载(登录用户id,用户名称).签名(密文)
     * @param userId  用户id
     * @param username 用户名称
     * @return 令牌字符串
     */
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder().
                setSubject("USER_INFO").
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim("userId", userId).  //Claims extends Map<String, Object>
                claim("username", username).
                signWith(tokenSignKey).
                compressWith(CompressionCodecs.GZIP).
                compact();
        return token;
    }

    /**
     * 解析令牌，辨别真伪。返回负载(Map)
     * @param token 令牌
     * @return Claims extends Map<String, Object>
     */
    public static Claims parseToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().
                    setSigningKey(tokenSignKey).
                    build().parseClaimsJws(token);
            return claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.PARAM_ERROR.getCode(), ResultCodeEnum.TOKEN_EXPIRED.getMessage());
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID.getCode(), ResultCodeEnum.TOKEN_INVALID.getMessage());
        }
    }
}